import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Option from './Option'
import './Select.scss'

class Select extends Component {
  static propTypes = {
    value: PropTypes.any.isRequired,
    onChange: PropTypes.func,
    placeholder: PropTypes.string,
    className: PropTypes.string,
    warpperStyle: PropTypes.object,
    style: PropTypes.object,
    children: PropTypes.any.isRequired,
  };

  static defaultProps = {
    onChange() {},
    placeholder: '',
    className: '',
    warpperStyle: {},
    style: {},
    value: '',
  };

  static Option = Option;

  constructor(props) {
    super(props)
    this.state = {
      value: props.value,
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) {
      this.setState({ value: nextProps.value })
    }
  }

  onChange = (e) => {
    const value = e.target.value
    this.setState({
      value,
    })
    this.props.onChange(value)
  }

  render() {
    const { children, placeholder, warpperStyle, style, className } = this.props

    return (
      <div styleName="selectWrapper" style={warpperStyle} className={className}>
        <select
          styleName="select"
          onChange={this.onChange}
          value={this.state.value}
          style={style}
        >
          <option value="" disabled hidden>{placeholder}</option>
          {children}
        </select>
      </div>
    )
  }
}

export default Select
